package org.csu.persistence.IMPL;

import org.csu.db.DBUtils;
import org.csu.domain.Sequence;
import org.csu.persistence.SequenceDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SequenceDAOImpl implements SequenceDAO {
    private static final String GETSEQUENCE = "SELECT * FROM sequence WHERE name=?";
    private static final String UPDATESEQUENCE = "UPDATE sequence SET name=?,nextid=? WHERE name=?";
    @Override
    public Sequence getSequence(Sequence sequence) {
        Sequence sequence1 = null;
        try {
            Connection connection = DBUtils.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(GETSEQUENCE);
            preparedStatement.setString(1,sequence.getName());
            ResultSet resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                sequence1 = new Sequence();
                sequence1.setName(resultSet.getString(1));
                sequence1.setNextId(resultSet.getInt(2));
            }
            resultSet.close();
            preparedStatement.close();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return sequence1;
    }

    @Override
    public void updateSequence(Sequence sequence) {
        try {
            Connection connection = DBUtils.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(UPDATESEQUENCE);
            preparedStatement.setString(1, sequence.getName());
            preparedStatement.setInt(2, sequence.getNextId());
            preparedStatement.setString(3, sequence.getName());
            preparedStatement.executeUpdate();
            DBUtils.closePreparedStatement(preparedStatement);
            DBUtils.closeConnection(connection);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
